from bokeh.models import ColumnDataSource, NumeralTickFormatter, SingleIntervalTicker
from bokeh.plotting import output_notebook,show,figure
from bokeh.models import FixedTicker
import pandas as pd
from pandas import Series,DataFrame
import numpy as np
import requests
from flask import Flask,render_template
from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.globals import ThemeType  
from openpyxl import Workbook
from bokeh.embed import components
from bokeh.resources import INLINE
import xlrd
import json
from pyecharts.charts import Bar
import pyecharts.options as opts
from pyecharts.charts import Pie
from pyecharts.charts import TreeMap
from pyecharts.charts import WordCloud
from pyecharts.charts import Scatter





def index():
    url2='https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=chinaDayListNew,chinaDayAddListNew&limit=30'
    response = requests.get(url2, verify=False)
    json_data = response.json()
    json_data['data']
    date=[]
    confirm=[]
    dead=[]
    heal=[]
    localadd=[]
    localcomfirm=[]
    data=json_data['data']['chinaDayAddListNew']
    for i in range(len(data)):
        date.append(data[i]['date'])
        confirm.append(data[i]['confirm'])
        dead.append(data[i]['dead'])
        heal.append(data[i]['heal'])
        localadd.append(data[i]['localinfectionadd'])
        localcomfirm.append(data[i]['localConfirmadd'])
    rq=[]
    for i in range(30):
        year=data[i]['y']
        rq.append(year+'-'+date[i].replace('.','-'))
    df={
    '日期':rq,
    '确诊':confirm,
    '死亡':dead,
    '康复':heal,
    '新增无症状':localadd,
    '新增确诊':localcomfirm
}
    df = DataFrame(df)
    return df

def one():
    df = index()
    data=[]
    for i in range(30):
        a=df['康复'].to_list()[i]-df['新增确诊'].to_list()[i]-df['新增无症状'].to_list()[i]
        data.append(a)
    y_in=[]
    y_out=[]
    kf=data
    data=data[15:30]
    for a in data:
        if a>=0:
            y_in.append(a)
            y_out.append("-")
        else:
            y_in.append("-")
            y_out.append(a)
    x_data = df['日期'].tail(15).to_list()
    bar = (
        Bar(init_opts=opts.InitOpts(width="2000px", height="1000px", bg_color="white"))
        .add_xaxis(xaxis_data=x_data)
        .add_yaxis(
            series_name="",
            y_axis=y_in,
            stack="Total",
            itemstyle_opts=opts.ItemStyleOpts(color="rgba(0,0,0,0)"),
        )
        .add_yaxis(series_name="康复>感染", y_axis=y_in, stack="Total",color="red")
        .add_yaxis(series_name="感染>康复", y_axis=y_out, stack="Total",color="#00CD96")
        .set_global_opts(yaxis_opts=opts.AxisOpts(type_="value"))
    #     .render("瀑布柱状图.html")
    )
    bar.render('bar.html')
    with open("bar.html", encoding="utf8", mode="r") as f:
        plot_a = "".join(f.readlines())
    日期=df['日期'].to_list()
    康复=df['康复'].to_list()
    确诊=df['新增确诊'].to_list()
    无症状=df['新增无症状'].to_list()
    contents=[]
    for i in range(30):
        contents.append([i+1])
    for a in range(30):
        contents[a].append(日期[a])
        contents[a].append(康复[a])
        contents[a].append(确诊[a])
        contents[a].append(无症状[a])
        contents[a].append(kf[a])
    titles=('序号','日期','新增确诊','新增无症状','康复','康复趋势')
    return (plot_a,titles,contents)

def two():
    df = index()
    date_array=np.array(df['日期'],dtype=np.datetime64)
    xzw_array=np.array(df['新增无症状'])
    zz_source = ColumnDataSource(data=dict(
    date = date_array,
    xzw= xzw_array,
    ))
    TOOLS="pan,box_zoom,reset,save,hover"
    p=figure(tools=TOOLS,plot_width=2000,plot_height=800,x_axis_type="datetime",
             tooltips=[('日期','@date{%F}'),('新增无症状人数','@xzw')]) 
    p.hover.mode = 'mouse'
    p.hover.formatters = { '@date': 'datetime'}
    p.yaxis.axis_label = '新增无症状人数'
    p.title.text = '近一个月新冠新增无症状人数'
    # 绘图
    p.line(x='date', y='xzw', color='#483D8B', line_dash=[6,3],line_width=3, source=zz_source)
    p.circle(x='date', y='xzw', source=zz_source, size=20, line_color='#DAA520',fill_color='white',alpha=0.8)
    # 5. 图形的额外设置
    p.legend.location='top_left'
    p.legend.click_policy = 'hide'
    p.xaxis.major_label_orientation = 1 # x轴标签旋转
    p.xgrid.grid_line_color = None
    return (p,df)

def wu():
    url='https://api.inews.qq.com/newsqa/v1/automation/modules/list?modules=FAutoCountryConfirmAdd,WomWorld,WomAboard'
    response = requests.get(url, verify=False)
    json_data = response.json()
    g=[]
    n=[]
    for i in range(15):
        g.append(json_data['data']['WomAboard'][i]['name'])
        n.append(json_data['data']['WomAboard'][i]['confirm'])
    c = (
    Pie()
    .add(
        "",
        [list(z) for z in zip(g, n)],
        center=["35%", "50%"],
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="累计确诊数量前15的国家"),
        legend_opts=opts.LegendOpts(pos_left="15%"),
    )
    .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
    .render("累计确诊数量前15的国家.html")
)
    with open("累计确诊数量前15的国家.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    contents=[]
    for i in range(15):
        contents.append([i+1])
    for a in range(15):
        contents[a].append(g[a])
        contents[a].append(n[a])
    titles=('序号','国家','累计确诊数量')
    return (plot_a,titles,contents)

def three():
    df=index()
    date_array=np.array(df['日期'],dtype=np.datetime64)
    confirm_array=np.array(df['确诊'])
    dead_array=np.array(df['死亡'])
    heal_array=np.array(df['康复'])
    xzw_array=np.array(df['新增无症状'])
    qz_array=np.array(df['新增确诊'])
    heal_source = ColumnDataSource(data=dict(
    date = date_array,
    heal= heal_array,
    ))
    TOOLS="pan,box_zoom,reset,save,hover"
    p=figure(tools=TOOLS,plot_width=2000,plot_height=800,x_axis_type="datetime",
             tooltips=[('日期','@date{%F}'),('康复人数','@heal')]) 
    p.hover.mode = 'mouse'
    p.hover.formatters = { '@date': 'datetime'}
    p.yaxis.axis_label = '康复人数'
    p.title.text = '近一个月新冠康复人数'
    p.line(x='date', y='heal', color='#32CD32', line_width=3, line_dash=[10,2],source=heal_source)
    p.diamond(x='date', y='heal', source=heal_source, size=20, line_color='#D2691E',fill_color='white',alpha=0.8)
    p.legend.location='top_left'
    p.legend.click_policy = 'hide'
    p.xaxis.major_label_orientation = 1 # x轴标签旋转
    p.xgrid.grid_line_color = None
    return (p,df)

def fourteen():
    df=index()
    date_array=np.array(df['日期'],dtype=np.datetime64)
    dead_array=np.array(df['死亡'])
    heal_source = ColumnDataSource(data=dict(
    date = date_array,
    dead= dead_array,
    ))
    TOOLS="pan,box_zoom,reset,save,hover"
    p=figure(tools=TOOLS,plot_width=2000,plot_height=800,x_axis_type="datetime",
             tooltips=[('日期','@date{%F}'),('康复人数','@dead')]) 
    p.hover.mode = 'mouse'
    p.hover.formatters = { '@date': 'datetime'}
    p.yaxis.axis_label = '死亡人数'
    p.title.text = '近一个月新冠死亡人数'
    p.line(x='date', y='dead', color='red', line_dash=[6,3],line_width=3, source=heal_source)
    p.circle(x='date', y='dead', source=heal_source, size=20, line_color='blue',fill_color='white',alpha=0.8)
    p.legend.location='top_left'
    p.legend.click_policy = 'hide'
    p.xaxis.major_label_orientation = 1 # x轴标签旋转
    p.xgrid.grid_line_color = None
    return (p,df)

def fifteen():
    df = index()
    date_array=np.array(df['日期'],dtype=np.datetime64)
    qz_array=np.array(df['新增确诊'])
    zz_source = ColumnDataSource(data=dict(
    date = date_array,
    qz= qz_array,
    ))
    TOOLS="pan,box_zoom,reset,save,hover"

    # 画布
    p=figure(tools=TOOLS,plot_width=2000,plot_height=800,x_axis_type="datetime",
             tooltips=[('日期','@date{%F}'),('新增确诊人数','@qz')]) 
    p.hover.mode = 'mouse'
    p.hover.formatters = { '@date': 'datetime'}
    p.yaxis.axis_label = '新增确诊人数'
    p.title.text = '近一个月新冠新增确诊人数'

    # 绘图
    p.line(x='date', y='qz', color='#FF1493', line_dash=[6,3],line_width=3, source=zz_source)
    p.triangle(x='date', y='qz', source=zz_source, size=20, line_color='#9400D3',fill_color='white',alpha=0.8)

    # 5. 图形的额外设置
    p.legend.location='top_left'
    p.legend.click_policy = 'hide'
    p.xaxis.major_label_orientation = 1 # x轴标签旋转
    p.xgrid.grid_line_color = None
    return (p,df)


def four():
    url = 'https://c.m.163.com/ug/api/wuhan/app/data/list-by-area-code?areaCode=66&t=1637576349190'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'
    }
    reponse = requests.get(url,headers=headers).text
    result = json.loads(reponse)
    data = result['data']
    wb = Workbook()
    ws = wb.active
    ws.title = "全国每日疫情数据"
    ws.append(['日期','确诊','疑似确诊','治愈','死亡','境外输入'])    
    for i in range(len(data['list'])):
        temp_list = [data['list'][i]['date'],
                     data['list'][i]['today']['confirm'],
                     data['list'][i]['today']['suspect'],
                     data['list'][i]['today']['heal'],
                     data['list'][i]['today']['dead'],
                     data['list'][i]['today']['input']]
        ws.append(temp_list)
    wb.save("全国每日疫情数据.xlsx")
    url_word = 'https://c.m.163.com/ug/api/wuhan/app/data/list-total?t=327516267367'
    response = requests.get(url_word,headers=headers).text
    result = json.loads(response)
    city_data = result['data']['areaTree'][2]['children']
    wb = Workbook()
    ws = wb.active
    ws.title = "全国各省累计疫情数据"
    ws.append(['地区','累计确诊','累计治愈','累计死亡'])
    for i in range(len(city_data)):
        temp_list = [city_data[i]['name'],
                     city_data[i]['total']['confirm'],
                     city_data[i]['total']['heal'],
                     city_data[i]['total']['dead']]
        ws.append(temp_list)
    wb.save("全国各省累计疫情数据.xlsx")
    province=pd.DataFrame(pd.read_excel('全国各省累计疫情数据.xlsx'))
    file = xlrd.open_workbook('全国各省累计疫情数据.xlsx')
    sheet = file.sheet_by_name('全国各省累计疫情数据')
    cityname = sheet.col_values(0) #取城市名字
    number = sheet.col_values(1)  #取累计确诊人数
    data = []
    for i in range(1, len(cityname)):
        list = []
        list.append(cityname[i])
        list.append(number[i])
        data.append(list)
     
    # 设置地图参数
    map = (
        Map(init_opts=opts.InitOpts(bg_color="#FFFAFA", theme=ThemeType.ESSOS, width="1000"))
            .add("累计确诊", data)
            .set_global_opts(
            title_opts=opts.TitleOpts("国内数据的疫情图"),
            visualmap_opts=opts.VisualMapOpts(
                is_piecewise=True,  
                pieces=[
                    {"min": 100000, "label": '>100000人', "color": "#8B0000"},
                    {"min": 10000, "max": 99999, "label": '10000-99999人', "color": "#FF0000"}, 
                    {"min": 1000, "max": 9999, "label": '1000-9999人', "color": "#FF6347"},
                    {"min": 100, "max": 999, "label": '100-999人', "color": "#FFD700"},
                    {"min": 10, "max": 99, "label": '10-99人', "color": "#F5DEB3"},
                    {"min": 1, "max": 9, "label": '1-9人', "color": "#FDF5E6"},
                ],
                range_text=['高', '低'],
            ),
        )
    )
    # map.render_notebook()
    map.render('map.html')
    with open("map.html", encoding="utf8", mode="r") as f:
        plot_a = "".join(f.readlines())
    df=pd.DataFrame(pd.read_excel('全国各省累计疫情数据.xlsx'))
    地区=df['地区'].to_list()
    确诊=df['累计确诊'].to_list()
    治愈=df['累计治愈'].to_list()
    contents=[]
    for i in range(len(地区)):
        contents.append([i])
    for a in range(len(地区)):
        contents[a].append(地区[a])
        contents[a].append(确诊[a])
        contents[a].append(治愈[a])
    titles=('序号','地区','累计确诊','累计治愈')
    return (plot_a,titles,contents)


def six():
    url='https://api.inews.qq.com/newsqa/v1/automation/modules/list?modules=FAutoCountryConfirmAdd,WomWorld,WomAboard'
    response = requests.get(url, verify=False)
    json_data = response.json()
    g=[]
    n=[]
    for i in range(15):
        g.append(json_data['data']['WomAboard'][i]['name'])
        n.append(json_data['data']['WomAboard'][i]['confirm'])
    c = (
    Scatter()
    .add_xaxis(g)
    .add_yaxis("累计确诊数量", n)
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Scatter-显示分割线"),
        xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(is_show=True)),
        yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(is_show=True)),
    )
    .render("top.html")
)
    with open("top.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    contents=[]
    for i in range(15):
        contents.append([i+1])
    for a in range(15):
        contents[a].append(g[a])
        contents[a].append(n[a])
    titles=('序号','国家','累计确诊数量')
    return (plot_a,titles,contents)

def seven():
    df = index()
    rq=df['日期'].tail(7).to_list()
    wzz=df['新增无症状'].tail(7).to_list()
    qz=df['新增确诊'].tail(7).to_list()
    c = (
        Bar()
        .add_xaxis(
            rq
        )
        .add_yaxis("新增无症状人数", wzz)
        .add_yaxis("新增确诊人数", qz)
        .set_global_opts(
            xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-15)),
            title_opts=opts.TitleOpts(title="近一周新增无症状与确诊人数", subtitle="对比"),
        )
        .render("db1.html")
    )
    with open("db1.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    contents=[]
    for i in range(len(rq)):
        contents.append([i])
    for a in range(len(rq)):
        contents[a].append(rq[a])
        contents[a].append(wzz[a])
        contents[a].append(qz[a])
    titles=('序号','日期','无症状新增人数','确诊人数')
    return (plot_a,titles,contents
        )

def eight():
    url='https://api.inews.qq.com/newsqa/v1/automation/modules/list?modules=FAutoCountryConfirmAdd,WomWorld,WomAboard'
    response = requests.get(url, verify=False)
    json_data = response.json()
    json_data['data']['WomAboard'][0]['confirm']
    c=[]
    g=[]
    for i in range(225):
        g.append(json_data['data']['WomAboard'][i]['name'])
        c.append(json_data['data']['WomAboard'][i]['confirmAdd'])
    dict = {g[i]:c[i] for i in range(len(g))}
    a1 = sorted(dict.items(), key=lambda x: x[1], reverse=True)
    # 按照字典的键进行排序
    g=[]
    c=[]
    for i in range(15):
        g.append(a1[i][0])
        c.append(a1[i][1])
    x_data = g
    y_data = c
    data_pair = [list(z) for z in zip(x_data, y_data)]
    data_pair.sort(key=lambda x: x[1])

    (
        Pie(init_opts=opts.InitOpts(width="2000px", height="1000px", bg_color="white"))
        .add(
            series_name="国家：",
            data_pair=data_pair,
            rosetype="radius",
            radius="55%",
            center=["50%", "50%"],
            label_opts=opts.LabelOpts(is_show=False, position="center"),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title="单日患者确诊人数排名前10的国家",
                pos_left="center",
                pos_top="20",
                title_textstyle_opts=opts.TextStyleOpts(color="black"),
            ),
            legend_opts=opts.LegendOpts(is_show=False),
        )
        .set_series_opts(
            tooltip_opts=opts.TooltipOpts(
                trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)"
            ),
            label_opts=opts.LabelOpts(color="black",font_size = 24),
        )
        .render('rose.html')
    )
    with open("rose.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    contents=[]
    for i in range(15):
        contents.append([i+1])
    for a in range(15):
        contents[a].append(g[a])
        contents[a].append(c[a])
    titles=('序号','国家','新增确诊人数')
    wz='以下国家是新冠单日感染人数数量前十的国家，说明该些国家的防疫力度不够，其中'+g[0]+'、'+g[1]+'单日新增人数最多，具体数据可查看上方可视化图表和下方表格。'
    return(plot_a,titles,contents,wz)

def nine():
    url='https://api.inews.qq.com/newsqa/v1/automation/modules/list?modules=VaccineSituationData'
    response = requests.get(url, verify=False)
    json_data = response.json()
    data=[]
    for i in range(30):
        data.append({"value":json_data['data']['VaccineSituationData'][i]['total_vaccinations'],"name":json_data['data']['VaccineSituationData'][i]['country']})
    c = (
        TreeMap(init_opts=opts.InitOpts(width="1600px", height="800px", bg_color="white"))
        .add("全球接种新馆疫苗数量前15的国家", data)
    .render("vaccine.html"))
    with open("vaccine.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    contents=[]
    for i in range(30):
        contents.append([i+1])
    for a in range(30):
        contents[a].append(data[a]['name'])
        contents[a].append(data[a]['value'])
    titles=('序号','国家名称','已接种疫苗数量')
    return (plot_a,titles,contents)


def ten():
    with open("j.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    df_境外=pd.DataFrame(pd.read_excel('data/新冠数据信息.xlsx'))[['日期','境外输入']]
    contents=[]
    for i in range(30):
        contents.append([i+1])
    for a in range(30):
        contents[a].append(df_境外['日期'].to_list()[a])
        contents[a].append(df_境外['境外输入'].to_list()[a])
    titles=('序号','日期','境外输入')
    return (plot_a,titles,contents)

def eleven():
    url='https://api.inews.qq.com/newsqa/v1/automation/modules/list?modules=VaccineSituationData'
    response = requests.get(url, verify=False)
    json_data = response.json()
    data=[]
    for i in range(len(json_data['data']['VaccineSituationData'])):
        for a in json_data['data']['VaccineSituationData'][i]['vaccinations'].split(','):
            data.append(a)
    data_dict ={}
    for key in data:
        data_dict[key]= data_dict.get(key,0)+1
    a1 = sorted(data_dict.items(), key=lambda x: x[1], reverse=True)
    (
        WordCloud(init_opts=opts.InitOpts(width="2000px", height="1000px"))
        .add(series_name="疫苗名称", data_pair=a1, word_size_range=[20, 66])
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title="各国接种疫苗统计", title_textstyle_opts=opts.TextStyleOpts(font_size=23)
            ),
            tooltip_opts=opts.TooltipOpts(is_show=True),
        )
        .render('word.html')
    )
    with open("word.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    contents=[]
    for i in range(len(a1)):
        contents.append([i+1])
    for a in range(len(a1)):
        contents[a].append(a1[a][0])
        contents[a].append(a1[a][1])
    titles=('序号','疫苗公司名称','选择接种国家的数量')
    return (plot_a,titles,contents)

def twelve():
    with open("pie.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    df_表2=pd.DataFrame(pd.read_excel('data/疫苗.xlsx'))
    a1=df_表2['国家'].to_list()
    b=df_表2['累计确诊'].to_list()
    contents=[]
    for i in range(10):
        contents.append([i+1])
    for a in range(10):
        contents[a].append(a1[a])
        contents[a].append(b[a])
    titles=('序号','国家','累计确诊数量')
    return (plot_a,titles,contents)
